<?php
namespace addons\wdsxh\library;
use think\Exception;

class Posters{
    /*
     * 创建海报
     */
    public static function create($poster_id,$qrcode=null,$avatar=null,$nickname='',$banner='',$title='',$filename=null,$savepath=null){
        $result=null;
        try{
            if($qrcode && self::isRemoteUrl($qrcode)){
                $qrcode=self::remoteUrlToLocal($qrcode,RUNTIME_PATH.'temp'.DS);
            }
            if($avatar && self::isRemoteUrl($avatar)){
                $avatar=self::remoteUrlToLocal($avatar,RUNTIME_PATH.'temp'.DS);
            }
            if($poster_id == 3) {
                $data = [
                    'bg'=>[
                        'img'=>'/assets/addons/wdsxh/img/poster_background.jpg',
                        'width'=>373,
                    ],
                    'data'=>[
                        [
                            'left'=>'44px',
                            'top' => '82px',
                            'type' => 'img',
                            'item' => 'avatar',
                            'lab' => '用户头像',
                            'width' => '59px',
                            'height' => '60px',
                            'model' => 0
                        ],
                        [
                            'left'=>'116px',
                            'top' => '99px',
                            'type' => 'text',
                            'item' => 'nickname',
                            'lab' => '用户昵称',
                            'width' => '116px',
                            'height' => '43px',
                            'size' => '16px',
                            'color'=>'#fafafa',
                        ],
                        [
                            'left'=>'241px',
                            'top' => '413px',
                            'type' => 'img',
                            'item' => 'qr',
                            'lab' => '二维码',
                            'width' => '80px',
                            'height' => '80px',
                        ],
                        [
                            'left'=>'36px',
                            'top' => '163px',
                            'type' => 'img',
                            'item' => 'banner',
                            'lab' => 'Banner图',
                            'width' => '302px',
                            'height' => '140px',
                        ],
                        [
                            'left'=>'36px',
                            'top' => '317px',
                            'type' => 'text',
                            'item' => 'title',
                            'lab' => '标题',
                            'width' => '182px',
                            'height' => '38px',
                            'size' => '18px',
                            'color'=>'#239494',
                        ],
                    ]
                ];
            } elseif ($poster_id == 2) {
                $data = [
                    'bg'=>[
                        'img'=>'/assets/addons/wdsxh/img/poster_background.jpg',
                        'width'=>373,
                    ],
                    'data'=>[
                        [
                            'left'=>'50px',
                            'top' => '85px',
                            'type' => 'img',
                            'item' => 'avatar',
                            'lab' => '用户头像',
                            'width' => '45px',
                            'height' => '47px',
                            'model' => 0
                        ],
                        [
                            'left'=>'117px',
                            'top' => '100px',
                            'type' => 'text',
                            'item' => 'nickname',
                            'lab' => '用户昵称',
                            'width' => '134px',
                            'height' => '28px',
                            'size' => '13px',
                            'color'=>'#000000',
                        ],
                        [
                            'left'=>'243px',
                            'top' => '416px',
                            'type' => 'img',
                            'item' => 'qr',
                            'lab' => '二维码',
                            'width' => '80px',
                            'height' => '80px',
                        ],
                        [
                            'left'=>'35px',
                            'top' => '168px',
                            'type' => 'img',
                            'item' => 'banner',
                            'lab' => 'Banner图',
                            'width' => '299px',
                            'height' => '145px',
                        ],
                        [
                            'left'=>'34px',
                            'top' => '334px',
                            'type' => 'text',
                            'item' => 'title',
                            'lab' => '标题',
                            'width' => '211px',
                            'height' => '34px',
                            'size' => '10px',
                            'color'=>'#000000',
                        ],
                    ]
                ];
            } else {
                $data = [
                    'bg'=>[
                        'img'=>'/assets/addons/wdsxh/img/poster_background.jpg',
                        'width'=>373,
                    ],
                    'data'=>[
                        [
                            'left'=>'45px',
                            'top' => '82px',
                            'type' => 'img',
                            'item' => 'avatar',
                            'lab' => '用户头像',
                            'width' => '57px',
                            'height' => '57px',
                            'model' => 0
                        ],
                        [
                            'left'=>'116px',
                            'top' => '102px',
                            'type' => 'text',
                            'item' => 'nickname',
                            'lab' => '用户昵称',
                            'width' => '134px',
                            'height' => '30px',
                            'size' => '16px',
                            'color'=>'#000000',
                        ],
                        [
                            'left'=>'244px',
                            'top' => '414px',
                            'type' => 'img',
                            'item' => 'qr',
                            'lab' => '二维码',
                            'width' => '80px',
                            'height' => '80px',
                        ],
                        [
                            'left'=>'31px',
                            'top' => '158px',
                            'type' => 'img',
                            'item' => 'banner',
                            'lab' => 'Banner图',
                            'width' => '314px',
                            'height' => '150px',
                        ],
                        [
                            'left'=>'31px',
                            'top' => '320px',
                            'type' => 'text',
                            'item' => 'title',
                            'lab' => '标题',
                            'width' => '241px',
                            'height' => '62px',
                            'size' => '16px',
                            'color'=>'#000000',
                        ],
                    ]
                ];
            }

            $bgImg=ROOT_PATH.'public'.$data['bg']['img'];
            if(!file_exists($bgImg)){
                throw new Exception('海报背景图片不存在');
            }
            ini_set('memory_limit','2048M');

            $mainLayer = \PHPImageWorkshop\ImageWorkshop::initFromPath($bgImg);

            $mainLayer->resizeInPixel($data['bg']['width'], null, true);
            $Layer=array();
            foreach ($data['data'] as $k=>$row){
                if(in_array($row['type'],array('img','text'))){
                    switch ($row['item']){
                        case 'avatar':
                            if(empty($avatar)){
                                break;
                            }
                            if($row['model']){
                                $Layer[$k]=\PHPImageWorkshop\ImageWorkshop::initFromPath($avatar);
                            }else{
                                $Layer[$k]=\PHPImageWorkshop\ImageWorkshop::initFromResourceVar(self::radius_img($avatar));
                            }
                            $Layer[$k]->resizeInPixel(intval($row['width']), intval($row['height']), false);
                            $mainLayer->addLayerOnTop($Layer[$k], intval($row['left']), intval($row['top']), 'LT');
                            break;
                        case 'qr':
                            if(empty($qrcode)){
                                break;
                            }
                            $Layer[$k]=\PHPImageWorkshop\ImageWorkshop::initFromPath($qrcode);
                            $Layer[$k]->resizeInPixel(intval($row['width']), intval($row['height']), false);
                            $mainLayer->addLayerOnTop($Layer[$k],  intval($row['left']),intval($row['top']), 'LT');
                            break;
                        case 'banner':
                            if(empty($banner)){
                                break;
                            }
                            $Layer[$k]=\PHPImageWorkshop\ImageWorkshop::initFromPath($banner);
                            $Layer[$k]->resizeInPixel(intval($row['width']), intval($row['height']), false);
                            $mainLayer->addLayerOnTop($Layer[$k],  intval($row['left']),intval($row['top']), 'LT');
                            break;
                        case 'nickname':
                            if(empty($nickname)){
                                break;
                            }
                            $text = $nickname;
                            $fontPath = ROOT_PATH.'public'.DS.'assets'.DS.'fonts'.DS.'SourceHanSansK-Regular.ttf';
                            $fontSize = intval($row['size']);
                            $fontColor = substr($row['color'],1);
                            $textRotation = 0;
                            $backgroundColor = null;
                            $Layer[$k] = \PHPImageWorkshop\ImageWorkshop::initTextLayer($text, $fontPath, $fontSize, $fontColor, $textRotation, $backgroundColor);
                            $mainLayer->addLayerOnTop($Layer[$k],intval($row['left']), intval($row['top'])+6,'LT');
                            break;
                        case 'title':
                            if(empty($title)){
                                break;
                            }
                            $text = $title;
                            $fontPath = ROOT_PATH.'public'.DS.'assets'.DS.'fonts'.DS.'SourceHanSansK-Regular.ttf';
                            $fontSize = intval($row['size']);
                            $fontColor = substr($row['color'],1);
                            $textRotation = 0;
                            $backgroundColor = null;
                            $title_count = mb_strlen($title,'UTF-8');
                            if($title_count <= 15) {
                                $Layer[$k] = \PHPImageWorkshop\ImageWorkshop::initTextLayer($title, $fontPath, $fontSize, $fontColor, $textRotation, $backgroundColor);
                                $mainLayer->addLayerOnTop($Layer[$k],intval($row['left']), intval($row['top'])+6,'LT');
                            } else {
                                $first_title = mb_substr($title, 0, 15, 'utf-8');
                                $second_title = mb_substr($title, 15, $title_count-15, 'utf-8');
                                $Layer[$k] = \PHPImageWorkshop\ImageWorkshop::initTextLayer($first_title, $fontPath, $fontSize, $fontColor, $textRotation, $backgroundColor);
                                $mainLayer->addLayerOnTop($Layer[$k],intval($row['left']), intval($row['top'])+6,'LT');
                                $Layer[$k] = \PHPImageWorkshop\ImageWorkshop::initTextLayer($second_title, $fontPath, $fontSize, $fontColor, 1, $backgroundColor);
                                $mainLayer->addLayerOnTop($Layer[$k],intval($row['left']), intval($row['top'])+56,'LT');
                            }

                            break;
                    }
                }
            }
            $dirPath = empty($savepath)?ROOT_PATH.'public'.DS.'uploads'.DS.'wdsxh'.DS.'posters'.DS:$savepath;
            if(!is_dir($dirPath)){
                mkdir($dirPath,0777,true);
            }
            $filename =empty($filename)?time().mt_rand(1000,9999).".jpg":$filename;
            $mainLayer->save($dirPath, $filename, true, null, 100);
            $result=array(
                'file_path'=>$dirPath.$filename,
                'file_name'=>$filename,
                'path'=>'/uploads/wdsxh/posters/'.$filename,
                'url'=>$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/uploads/wdsxh/posters/'.$filename
            );
        }catch (Exception $e){
            die($e->getMessage());
        }
        return $result;
    }

    /**
     * 处理圆角图片
     * @param  string  $imgpath 源图片路径
     * @param  integer $radius  圆角半径长度默认为0,处理成圆型
     * @return [type]           [description]
     */
    public static function radius_img($imgpath = '', $radius = 0) {
        $ext     = pathinfo($imgpath);
        $src_img = null;
        if(!isset($ext['extension'])){
            $src_img = imagecreatefromjpeg($imgpath);
        }else{
            switch ($ext['extension']) {
                case 'jpg':
                    $src_img = imagecreatefromjpeg($imgpath);
                    break;
                case 'png':
                    $src_img = imagecreatefrompng($imgpath);
                    break;
                case 'gif':
                    $src_img = imagecreatefromgif($imgpath);
                    break;
                case 'wbpm':
                    $src_img = imagecreatefromwbmp($imgpath);
                    break;
                default:
                    $src_img = imagecreatefromjpeg($imgpath);
                    break;
            }
        }
        $wh = getimagesize($imgpath);
        $w  = $wh[0];
        $h  = $wh[1];

        $radius = $radius == 0 ? (min($w, $h) / 2) : $radius;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $radius; //圆 角半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                    //不在四角的范围内,直接画
                    imagesetpixel($img, $x, $y, $rgbColor);
                } else {
                    //在四角的范围内选择画
                    //上左
                    $y_x = $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //上右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下左
                    $y_x = $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                }
            }
        }
        return $img;
    }

    public static function isRemoteUrl($url)
    {
        return stripos($url, 'http://')  === 0 || stripos($url, 'https://') === 0;
    }

    public static function remoteUrlToLocal($url,$save_dir='',$filename='',$type=0){
        if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
        }
        if(trim($save_dir)==''){
            $save_dir='./';
        }
        if(trim($filename)==''){
            $ext=strrchr($url,'.');
            if($ext!='.gif' && $ext!='.jpg' && $ext!='.png'){
                $filename=time().'.jpg';
            }else{
                $filename=time().$ext;
            }
        }
        /*
        if(0!==strrpos($save_dir,'/')){
            $save_dir.='/';
        }
        */
        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return array('file_name'=>'','save_path'=>'','error'=>5);
        }
        //获取远程文件所采用的方法
        if($type){
            $ch=curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,15);
            $img=curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $img=ob_get_contents();
            ob_end_clean();
        }
        //文件大小
        /*
        $fp2=@fopen($save_dir.$filename,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        */
        file_put_contents($save_dir.$filename,$img);
        unset($img,$url);
        //return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
        return $save_dir.$filename;
    }
}
